<<<<<<< HEAD
import numpy as np
import time

# 生成测试数据
size = 1000000  # 100万元素
a = np.random.rand(size)
b = np.random.rand(size)

# ================= 非向量化实现 (使用循环) =================
def non_vectorized_dot(a, b):
    result = 0
    for i in range(len(a)):
        result += a[i] * b[i]
    return result

# ================= 向量化实现 (使用NumPy) =================
def vectorized_dot(a, b):
    return np.dot(a, b)

# ================= 性能对比 =================
print("开始性能测试...")

# 测试非向量化版本
start_time = time.time()
result_loop = non_vectorized_dot(a, b)
loop_time = time.time() - start_time

# 测试向量化版本
start_time = time.time()
result_vec = vectorized_dot(a, b)
vec_time = time.time() - start_time

# 验证结果一致性
assert abs(result_loop - result_vec) < 1e-6

# 输出结果
print(f"计算结果: {result_vec:.4f}")
print(f"非向量化耗时: {loop_time:.6f} 秒")
print(f"向量化耗时: {vec_time:.6f} 秒")
=======
import numpy as np
import time

# 生成测试数据
size = 1000000  # 100万元素
a = np.random.rand(size)
b = np.random.rand(size)

# ================= 非向量化实现 (使用循环) =================
def non_vectorized_dot(a, b):
    result = 0
    for i in range(len(a)):
        result += a[i] * b[i]
    return result

# ================= 向量化实现 (使用NumPy) =================
def vectorized_dot(a, b):
    return np.dot(a, b)

# ================= 性能对比 =================
print("开始性能测试...")

# 测试非向量化版本
start_time = time.time()
result_loop = non_vectorized_dot(a, b)
loop_time = time.time() - start_time

# 测试向量化版本
start_time = time.time()
result_vec = vectorized_dot(a, b)
vec_time = time.time() - start_time

# 验证结果一致性
assert abs(result_loop - result_vec) < 1e-6

# 输出结果
print(f"计算结果: {result_vec:.4f}")
print(f"非向量化耗时: {loop_time:.6f} 秒")
print(f"向量化耗时: {vec_time:.6f} 秒")
>>>>>>> 237300619cb42005cc7f4bf2912e8423091ca02a
print(f"向量化加速比: {loop_time/vec_time:.1f} 倍")